package com.cskaoyan._03otherstream._03object;

import java.io.*;

/**
 * @description:
 * @author: 景天
 * @date: 2023/2/20 16:07
 **/
/*
使用对象流(序列化与反序列化流)
写入对象 读取对象
 */
public class Demo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 序列化
        serialize();

        // 反序列化操作
        unSerialize();


    }

    private static void unSerialize() throws IOException, ClassNotFoundException {
        // 创建反序列化流对象
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("a.txt"));
        // readObject()
        Object o = in.readObject();
        System.out.println(o);
        // close
        in.close();
    }

    private static void serialize() throws IOException {
        // 创建学生对象
        //Student student = new Student("zs", 20);
        Student student = new Student("ls", 21,59);
        // 创建序列化流对象
        ObjectOutputStream out =
                new ObjectOutputStream(new FileOutputStream("a.txt"));
        // writeObject(Object o)
        out.writeObject(student);
        // close
        out.close();
    }
}
/*
java.io.NotSerializableException 没有实现Serializable接口
 */
class Student implements Serializable {
    String name;
    int age;
    // 使用transient关键字 修饰不想被序列化的成员
    transient int score;
    // 显式声明
    static final long serialVersionUID = -4521843559819991272L;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student(String name, int age, int score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    //@Override
    //public String toString() {
    //    return "Student{" +
    //            "name='" + name + '\'' +
    //            ", age=" + age +
    //            '}';
    //}

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", score=" + score +
                '}';
    }
}
